package com.hn658.base.message.comet.servlet;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hn658.base.message.comet.context.RequestContext;
import com.hn658.base.message.common.enums.ServicesContants;
import com.hn658.base.message.notisender.sender.comet.AsyncContextCache;
import com.hn658.base.message.notisender.sender.comet.IIsOnlineManager;
import com.hn658.framework.logging.enums.LogCategory;

/**
 * 服务器端推送servlet
 *
 * @author Chengfei.Sun
 */
public class PushServiceServlet extends AbstractServlet {

	private static final long serialVersionUID = 6971557150330830099L;
	
	IIsOnlineManager isOnlineManager;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
   		super.init(config);
   		isOnlineManager = ac.getBean(IIsOnlineManager.class);
   	}
	
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	RequestContext requestContext = (RequestContext) request.getAttribute(ServicesContants.REQUEST_CONTEXT);
    	logger.debug(LogCategory.SYSTEM, "当前请求上下文信息 {}", requestContext);
    	
    	String uid = requestContext.getUid()+"";
        String appId = requestContext.getAppId()+"";
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setCharacterEncoding("UTF-8");
        
        //获取当前AsyncContext实例
        final AsyncContext asyncContext = request.startAsync();

        // 当前请求以设备号对应长连接
        logger.debug(LogCategory.SYSTEM, "创建长链接, userId :{}  appKey :{}", new Object[]{ uid, appId});
        AsyncContextCache.add(appId, uid, asyncContext, isOnlineManager);

    }
}
